import axios from 'axios'
import userUrl from '../../util/url.js'
import _ from 'lodash'

let url = userUrl + 'api.php/xiaoshou'

const xiaoshou = {
    namespaced: true,
    state: {
        list: [],
        form: {
            shuliang: 1,
        },
        modalShow: false,
        idArr: [],
        isupdate: false,
        upadd: {},
        currentPage: 1,
        pageSize: 5,
        total: 0
    },
    mutations: {
        setList(state, payload) {
            state.list = payload
        },
        setmodal(state, payload) {
            state.modalShow = payload
        },
        setform(state, payload) {
            state.form = payload
        },
        setidArr(state, payload) {
            let arr = []
            payload.map((item) => {
                arr.push(item.id)
            })
            state.idArr = arr
            state.upadd = _.cloneDeep(payload[0])
        },
        setisupdate(state, payload) {
            state.isupdate = payload
        },
        setTotal(state, payload) {
            state.total = payload
        },
        TocurrenPage(state, payload) {
            state.currentPage = payload
            console.log(state.currentPage)
        }
    },
    actions: {
        getList({ state, commit, dispatch }, payload) {
            return new Promise((resolve, reject) => {
                axios({
                    method: 'get',
                    url,
                    params: { transform: '1', order: 'id,desc', page: `${state.currentPage},${state.pageSize}`, }
                }).then(res => {
                    commit('setList', res.data.xiaoshou)
                    commit('setTotal', res.data._results)
                    resolve()
                })
            })
        },
        save({ state, commit, dispatch }, payload) {
            return new Promise((resolve, reject) => {
                let method = 'post',
                    url = userUrl + 'api.php/xiaoshou'
                if (state.isupdate) {
                    method = 'put',
                        url += '/' + state.form.id
                }
                axios({
                    method,
                    url,
                    data: state.form
                }).then(res => {
                    commit('setmodal', false)
                    dispatch('getList')
                    resolve()
                })
            })
        },
        del({ state, commit, dispatch }, payload) {
            return new Promise((resolve, reject) => {
                axios({
                    method: 'delete',
                    url: url + '/' + state.idArr,
                }).then(res => {
                    commit('setmodal', false)
                    dispatch('getList')
                    resolve()
                })
            })
        },
        handlerPage({ commit, dispatch, state }, page) {
            commit('TocurrenPage', page)
            dispatch('getList');
        },
    }
}
export default xiaoshou